package com.sany.taskmanager.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.view.View;

import com.sany.taskmanager.R;
import com.sany.taskmanager.bean.ColorBean;
import com.sany.taskmanager.bean.SendTaskBean;
import com.sany.taskmanager.bean.TaskInfoBean;
import com.sany.taskmanager.databinding.FragmentMaterialBinding;
import com.sany.taskmanager.http.IHttpCallBack;
import com.sany.taskmanager.room.TaskDatabase;
import com.sany.taskmanager.room.entity.LocalTaskInfo;
import com.sany.taskmanager.ui.activity.HistoryInfoActivity;
import com.sany.taskmanager.ui.activity.MainActivity;
import com.sany.taskmanager.ui.activity.SendedTaskActivity;
import com.sany.taskmanager.ui.adapter.TaskInfoAdapter;
import com.sany.taskmanager.ui.widget.ColorDialog;
import com.sany.taskmanager.ui.widget.ModifyTaskInfoDialog;
import com.sany.taskmanager.util.EditUtil;
import com.sany.taskmanager.util.GsonUtil;
import com.sany.taskmanager.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 按物料编码录入任务
 */
public class MaterialFragment extends BaseFragment<FragmentMaterialBinding> implements View.OnClickListener {

    private TaskInfoAdapter mAdapter;
    private List<LocalTaskInfo> mTaskList;
    private ColorBean mColorBean;
    private ColorBean mHeadColorBean;
    private String mMaterialNum;
    private int mBoomCount;
    private int mBoomType;
    private int mAllSelectStatus;

    private MainActivity mActivity;

    public MaterialFragment() {
    }

    public static MaterialFragment newInstance() {
        return new MaterialFragment();
    }

    @Override
    protected void initData() {
        mActivity = (MainActivity) getActivity();
        vBinding.etMaterialNum.setTransformationMethod(EditUtil.replacementTransformationMethod);
        vBinding.includeTitle.ivSelectAll.setOnClickListener(this);
        mAdapter = new TaskInfoAdapter(requireContext());
        mAdapter.setOnOperateListener(new TaskInfoAdapter.OnOperateListener() {
//            @Override
//            public void send(LocalTaskInfo item) {
//                mActivity.showTipDialog(getString(R.string.tip_send_task), () -> {
//                    sendSingTask(item);
//                });
//            }

            @Override
            public void modify(int position) {
                showModifyInventoryDialog(position);
            }

            @Override
            public void delete(LocalTaskInfo item) {
                mActivity.showTipDialog(getString(R.string.tip_delete_task), () -> {
                    // 从数据中，删除对应的数据
                    TaskDatabase.getInstance().getTaskDao().deleteTask(item);
                    // 刷新UI页面
                    mTaskList.remove(item);
                    mAdapter.setTaskList(mTaskList);
                    ToastUtil.showToast(requireContext(), getString(R.string.tip_delete_success));
                });
            }
        });
        vBinding.rvTaskInfo.setAdapter(mAdapter);

        vBinding.llNewBoom.setOnClickListener(this);
        vBinding.includeTitle.ivSelectAll.setOnClickListener(this);
        vBinding.ivScan.setOnClickListener(this);
        vBinding.rlBoomColor.setOnClickListener(this);
        vBinding.rlBoomHeadColor.setOnClickListener(this);
        vBinding.tvInput.setOnClickListener(this);
        vBinding.tvImport.setOnClickListener(this);
        vBinding.tvSendBatch.setOnClickListener(this);
        vBinding.tvHistoryInfo.setOnClickListener(this);
        vBinding.tvSendedTask.setOnClickListener(this);

        loadRoomData();
    }

    private void loadRoomData() {
        mTaskList = TaskDatabase.getInstance().getTaskDao().getMaterialTasks();
        refreshUI();
    }

    /**
     * 下发单个大臂
     */
//    private void sendSingTask(LocalTaskInfo item) {
//        SendTaskBean taskBean = GsonUtil.GsonToBean(GsonUtil.BeanToJson(item), SendTaskBean.class);
//        List<SendTaskBean> taskList = new ArrayList<>();
//        taskList.add(taskBean);
//        mActivity.showLoading();
//        mActivity.compositeDisposable.add(mActivity.taskViewModel.sendTask(taskList, new IHttpCallBack<Boolean>() {
//            @Override
//            public void onSuccess(Boolean aBoolean) {
//                mActivity.hideLoading();
//                // 跟新本地数据库
//                TaskDatabase.getInstance().getTaskDao().deleteTask(item);
//                // 刷新UI
//                mTaskList.remove(item);
//                mAdapter.setTaskList(mTaskList);
//                ToastUtil.showToast(requireContext(), getString(R.string.tip_send_success));
//            }
//
//            @Override
//            public void onFailed(String message) {
//                mActivity.hideLoading();
//                ToastUtil.showToast(requireContext(), String.format(getString(R.string.format_send_failed), message));
//            }
//        }));
//
//    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_select_all) {
            // 全选/全不选
            mAllSelectStatus = (mAllSelectStatus + 1) % 2;
            vBinding.includeTitle.ivSelectAll.setImageLevel(mAllSelectStatus);
            for (LocalTaskInfo item : mTaskList) {
                item.setSelected(mAllSelectStatus == 1);
            }
            mAdapter.setTaskList(mTaskList);
        } else if (id == R.id.iv_scan) {
            // 跳转到扫码页面
            mActivity.skip2Scan();
        } else if (id == R.id.rl_boom_color) {
            // 弹出大臂颜色选择对话框
            showColorDialog();
        } else if (id == R.id.rl_boom_head_color) {
            // 弹出大臂颜色选择对话框
            showHeadColorDialog();
        } else if (id == R.id.tv_input) {
            // 录入任务清单
            if (checkInput()) {
                // 添加数据：校验是否有重复录入
                if (checkAddTaskInfo(getTaskInfo())) {
                    // 刷新UI
                    refreshUI();
                }
            }
        } else if (id == R.id.tv_import) {
            // excel批量任务导入
            mActivity.checkPermission();
        } else if (id == R.id.tv_send_batch) {
            if (!existSelect()) {
                ToastUtil.showToast(requireContext(), getString(R.string.tip_select_batch_send_task_info));
                return;
            }
            mActivity.showTipDialog(getString(R.string.tip_send_selected_task), this::sendBatchTask);
        } else if (id == R.id.tv_history_info) {
            startActivity(new Intent(requireContext(), HistoryInfoActivity.class));
        } else if (id == R.id.tv_sended_task) {
            startActivity(new Intent(requireContext(), SendedTaskActivity.class));
        } else if (id == R.id.ll_new_boom) { // 勾选框：大臂是否为新品
            mBoomType = Math.abs(mBoomType - 1);
            vBinding.ivNewBoom.setVisibility(mBoomType == 1 ? View.VISIBLE : View.GONE);
        }
    }

    private LocalTaskInfo getTaskInfo() {
        LocalTaskInfo localTaskInfo = new LocalTaskInfo();
        localTaskInfo.setMaterialNum(mMaterialNum);
        localTaskInfo.setColorType(mColorBean.getColorType());
        localTaskInfo.setColorName(mColorBean.getColorName());
        localTaskInfo.setColorCode(mColorBean.getColorCode());
        localTaskInfo.setColorValue(mColorBean.getColorValue());
        localTaskInfo.setHeadColorType(mHeadColorBean.getColorType());
        localTaskInfo.setHeadColorName(mHeadColorBean.getColorName());
        localTaskInfo.setHeadColorCode(mHeadColorBean.getColorCode());
        localTaskInfo.setHeadColorValue(mHeadColorBean.getColorValue());
        localTaskInfo.setCount(mBoomCount);
        localTaskInfo.setBoomType(mBoomType);
        return localTaskInfo;
    }

    /**
     * 刷新列表
     */
    public void refreshUI() {
        // 刷新UI页面
        mAdapter.setTaskList(mTaskList);
        if (mTaskList == null || mTaskList.isEmpty()) {
            vBinding.viewEmpty.setVisibility(View.VISIBLE);
            vBinding.rvTaskInfo.setVisibility(View.GONE);
        } else {
            vBinding.viewEmpty.setVisibility(View.GONE);
            vBinding.rvTaskInfo.setVisibility(View.VISIBLE);
        }
        // 清空UI页面的数据
        clearUIData();
    }

    /**
     * 下发成套大臂
     */
    private void sendBatchTask() {
        List<LocalTaskInfo> subList = new ArrayList<>();
        for (int i = mTaskList.size() - 1; i >= 0; i--) {
            if (mTaskList.get(i).isSelected()) {
                subList.add(mTaskList.get(i));
            }
        }

        // 单个大臂不能以成套任务下发
//        if (subList.size() <= 1) {
//            ToastUtil.showToast(requireContext(), getString(R.string.tip_single_boom_cannot_send_with_batch));
//            return;
//        }

        List<SendTaskBean> taskList = GsonUtil.GsonToList(GsonUtil.BeanToJson(subList), SendTaskBean.class);
        mActivity.showLoading();
        mActivity.compositeDisposable.add(mActivity.taskViewModel.sendTask(taskList, new IHttpCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                mActivity.hideLoading();
                // 更新本地数据库
                TaskDatabase.getInstance().getTaskDao().deleteTasks(subList);
                // 刷新UI
                mTaskList.removeAll(subList);
                mAdapter.setTaskList(mTaskList);
                ToastUtil.showToast(requireContext(), getString(R.string.tip_batch_send_success));
            }

            @Override
            public void onFailed(String message) {
                mActivity.hideLoading();
                ToastUtil.showToast(requireContext(), message);
            }
        }));
    }

    public void refreshList(List<LocalTaskInfo> taskList) {
        // 更新数据列表
        for (LocalTaskInfo info : taskList) {
            checkAddTaskInfo(info);
        }
        // 更新UI
        refreshUI();
    }

    /**
     * 校验录入的任务清单，是否重复录入
     */
    public boolean checkAddTaskInfo(LocalTaskInfo localTaskInfo) {
        // 检查录入的任务列表中是否已存在该任务：不存在则直接插入数据；存在则提示是否新增
        for (LocalTaskInfo taskInfo : mTaskList) {
            if (taskInfo.getMaterialNum().equals(localTaskInfo.getMaterialNum()) && taskInfo.getColorType() == localTaskInfo.getColorType()
                    && taskInfo.getHeadColorType() == localTaskInfo.getHeadColorType() && taskInfo.getBoomType() == localTaskInfo.getBoomType()) {
                // 存在则提示是否新增，确认新增则数量合并
                mActivity.showTipDialog(getString(R.string.tip_exist_task_whether_add), () -> {
                    int count = taskInfo.getCount();
                    taskInfo.setCount(count + localTaskInfo.getCount());
                    TaskDatabase.getInstance().getTaskDao().updateTask(taskInfo);
                    refreshUI();
                });
                return false;
            }
        }
        // 如果录入的任务列表中不存在，则新增一条数据，写入到数据库中
        Long id = TaskDatabase.getInstance().getTaskDao().insertTask(localTaskInfo);
        localTaskInfo.setId(id);
        mTaskList.add(localTaskInfo);
        return true;
    }


    private void clearUIData() {
        vBinding.etMaterialNum.setText("");
        vBinding.viewColor.setVisibility(View.GONE);
        vBinding.tvColor.setVisibility(View.GONE);
        vBinding.viewHeadColor.setVisibility(View.GONE);
        vBinding.tvHeadColor.setVisibility(View.GONE);
        vBinding.etCount.setText("");
        vBinding.ivNewBoom.setVisibility(View.GONE);
        mColorBean = null;
        mMaterialNum = null;
        mBoomCount = 0;
        mBoomType = 0;
    }

    private boolean existSelect() {
        boolean existSelect = false;
        for (LocalTaskInfo item : mTaskList) {
            if (item.isSelected()) {
                existSelect = true;
                break;
            }
        }
        return existSelect;
    }

    /**
     * 校验录入信息的完整性
     */
    private boolean checkInput() {
        mMaterialNum = vBinding.etMaterialNum.getText().toString().toUpperCase().replaceAll(" ", "");
        if (mMaterialNum.length() == 0) {
            ToastUtil.showToast(requireContext(), getString(R.string.please_input_material_num));
            return false;
        }
        if (mHeadColorBean == null) {
            ToastUtil.showToast(requireContext(), getString(R.string.please_select_boom_head_color));
            return false;
        }
        if (mColorBean == null) {
            ToastUtil.showToast(requireContext(), getString(R.string.please_select_boom_color));
            return false;
        }
        String count = vBinding.etCount.getText().toString().replaceAll(" ", "");
        if (count.length() == 0) {
            ToastUtil.showToast(requireContext(), getString(R.string.please_input_boom_count));
            return false;
        }
        try {
            mBoomCount = Integer.parseInt(count);
            if (mBoomCount <= 0) {
                ToastUtil.showToast(requireContext(), getString(R.string.please_input_correct_boom_count));
                return false;
            }
        } catch (Exception e) {
            ToastUtil.showToast(requireContext(), getString(R.string.please_input_correct_boom_count));
            return false;
        }
        return true;
    }

    private ColorDialog colorDialog;

    /**
     * 大臂颜色选择弹框
     */
    private void showColorDialog() {
        if (colorDialog == null) {
            colorDialog = new ColorDialog(requireActivity());
            colorDialog.setOnSelectedColorListener(colorBean -> {
                mColorBean = colorBean;
                vBinding.viewColor.setVisibility(View.VISIBLE);
                vBinding.viewColor.setBgColor(Color.parseColor(colorBean.getColorValue()));
                vBinding.tvColor.setVisibility(View.VISIBLE);
                vBinding.tvColor.setText(colorBean.getColorCode());
            });
        }
        if (!colorDialog.isShowing()) {
            colorDialog.show();
        }
    }

    private ColorDialog headColorDialog;

    /**
     * 大臂颜色选择弹框
     */
    private void showHeadColorDialog() {
        if (headColorDialog == null) {
            headColorDialog = new ColorDialog(requireActivity());
            headColorDialog.setOnSelectedColorListener(colorBean -> {
                mHeadColorBean = colorBean;
                vBinding.viewHeadColor.setVisibility(View.VISIBLE);
                vBinding.viewHeadColor.setBgColor(Color.parseColor(colorBean.getColorValue()));
                vBinding.tvHeadColor.setVisibility(View.VISIBLE);
                vBinding.tvHeadColor.setText(colorBean.getColorCode());
            });
        }
        if (!headColorDialog.isShowing()) {
            headColorDialog.show();
        }
    }

    private ModifyTaskInfoDialog modifyTaskInfoDialog;
    private int currentPosition;

    /**
     * 修改大臂库位信息：主要修改大臂颜色和库位编号
     */
    private void showModifyInventoryDialog(int position) {
        currentPosition = position;
        if (modifyTaskInfoDialog == null) {
            modifyTaskInfoDialog = new ModifyTaskInfoDialog(requireActivity(), taskTransform(mTaskList.get(currentPosition)), true);
            modifyTaskInfoDialog.setOnModifyTaskInfoListener(new ModifyTaskInfoDialog.OnModifyTaskInfoListener() {
                @Override
                public void modifyTaskInfo(int colorType, String colorCode, String colorValue, int headColorType, String headColorCode, String headColorValue, String materialNum, int boomType, int count) {
                    mTaskList.get(currentPosition).setColorType(colorType);
                    mTaskList.get(currentPosition).setColorCode(colorCode);
                    mTaskList.get(currentPosition).setColorValue(colorValue);
                    mTaskList.get(currentPosition).setHeadColorType(headColorType);
                    mTaskList.get(currentPosition).setHeadColorCode(headColorCode);
                    mTaskList.get(currentPosition).setHeadColorValue(headColorValue);
                    mTaskList.get(currentPosition).setMaterialNum(materialNum);
                    mTaskList.get(currentPosition).setBoomType(boomType);
                    mTaskList.get(currentPosition).setCount(count);
                    // 刷新UI页面
                    mAdapter.setTaskList(mTaskList);
                    // 更新本地数据库
                    TaskDatabase.getInstance().getTaskDao().updateTask(mTaskList.get(currentPosition));
                    ToastUtil.showToast(requireContext(), getString(R.string.tip_modify_success));
                }

                @Override
                public void goScan() {
                    // 跳转到扫码页面
                    mActivity.skip2Scan();
                }
            });
        } else {
            modifyTaskInfoDialog.setTaskInfo(taskTransform(mTaskList.get(currentPosition)));
        }
        if (!modifyTaskInfoDialog.isShowing()) {
            modifyTaskInfoDialog.show();
        }

    }

    /**
     * 数据对象转换
     * LocalTaskInfo -> TaskInfoBean
     */
    private TaskInfoBean taskTransform(LocalTaskInfo localTaskInfo) {
        String json = GsonUtil.BeanToJson(localTaskInfo);
        return GsonUtil.GsonToBean(json, TaskInfoBean.class);
    }

    public void onScanSuccess(String barcode) {
        String materialNum = barcode.split("\\|")[0];
        vBinding.etMaterialNum.setText(materialNum);
        vBinding.etMaterialNum.setSelection(materialNum.length());
        // 修改下发任务信息的弹框，更新物料编码
        if (modifyTaskInfoDialog != null && modifyTaskInfoDialog.isShowing()) {
            modifyTaskInfoDialog.setMaterialNum(materialNum);
        }
    }

    public void refreshMaterialNum(String materialNum) {
        vBinding.etMaterialNum.setText(materialNum);
        vBinding.etMaterialNum.setSelection(materialNum.length());
        // 修改下发任务信息的弹框，更新物料编码
        if (modifyTaskInfoDialog != null && modifyTaskInfoDialog.isShowing()) {
            modifyTaskInfoDialog.setMaterialNum(materialNum);
        }
    }
}